package lumis.content.source.field;

import java.util.ArrayList;
import java.util.List;

import lumis.content.core.ContentTag;
import lumis.content.source.field.type.TagDataType;
import lumis.content.table.ContentQueryBuilder;
import lumis.doui.source.ISourceData;
import lumis.doui.source.field.type.SourceFieldTypes;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;

/**
 * Tag source field.
 * 
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class TagSourceField extends MetaDataSourceField 
{
	/**
	 * Tag source Field Constructor.
	 * @since 6.0.0
	 */
	public TagSourceField() throws PortalException
	{
		super(ContentQueryBuilder.CONTENT_LOCALE_RELATION_ID, "id", SourceFieldTypes.getInstance(TagDataType.class.getName()));
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void convertRowToFieldData(ISourceData databaseRow, ISourceData sourceRow) throws PortalException
	{
		// gets the contentLocaleId to be converted
		String contentLocaleId = (String)databaseRow.get(getId());
		
		// get contentTags for this content locale
		List<ContentTag> contentTags = ManagerFactory.getEntityManager().createQuery("select t from ContentTag t inner join t.contentVersion tcv, ContentLocale tcl, " +
									"ContentLocale cl inner join cl.tags ts where tcl.content = ts and tcv = tcl.activeVersion and cl.id = :contentLocaleId")
									.setParameter("contentLocaleId", contentLocaleId)
									.getResultList();

		// build a list of TagDataType.Data.Tag to be converted to TagDataType.Data.  
		List<TagDataType.Data.Tag> tags = new ArrayList<TagDataType.Data.Tag>(contentTags.size());
		for(ContentTag contentTag:contentTags)
		{
			TagDataType.Data.Tag tag = new TagDataType.Data.Tag();
			tag.setName(contentTag.getName());
			tags.add(tag);
		}
		TagDataType.Data data = new TagDataType.Data(tags);
		// put on source the value converted
		sourceRow.put(getId(), data);
	}
}
